package cn.com.fuhuitong.main.home.ui.activity

import cn.com.fuhuitong.R
import cn.com.fuhuitong.aroute.ARouteConstance
import cn.com.fuhuitong.main.ItemViewType
import cn.com.fuhuitong.main.base.ViewModeActivity
import cn.com.fuhuitong.main.home.adapter.SignInDateAdapter
import cn.com.fuhuitong.main.home.vm.SigInViewModel
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.vlayout.layout.GridLayoutHelper
import kotlinx.android.synthetic.main.activity_home_sign_in.*
import java.text.SimpleDateFormat
import androidx.lifecycle.Observer
import cn.com.fuhuitong.http.HttpResponseStatus
import java.util.*

@Route(path = ARouteConstance.ACTIVITY_URL_SIGN_UP)
class HomeSignUpActivity : ViewModeActivity<SigInViewModel>() {

    private val dateDays: MutableList<String> = mutableListOf("日", "一", "二", "三", "四", "五", "六")

    private lateinit var signInDateAdapter: SignInDateAdapter

    override fun viewModel(): SigInViewModel = createViewModel()

    override val layoutResId: Int
        get() = R.layout.activity_home_sign_in

    override fun initView() {

        image_sign_up_back.setOnClickListener {
            this.finish()
        }

        this.initViewRecyclerAdapter(
            recycler_sign_in_date, arrayOf(ItemViewType.SIGN_IN_DATE)
        )

        val helper = GridLayoutHelper(7)
        helper.setSpanSizeLookup(object : GridLayoutHelper.SpanSizeLookup() {
            override fun getSpanSize(position: Int): Int {
                return if (position == 7) getMontyFirstDayOfWeek(getYear(), getMonth()) else 1
            }
        })
        helper.vGap = resources.getDimensionPixelSize(R.dimen.dp_20)
        helper.setAutoExpand(false)
        delegateAdapter.addAdapter(SignInDateAdapter(this, helper)
            .apply {
                signInDateAdapter = this
            })

        for (index: Int in 1..getMontyCountDay(getYear(), getMonth())) {
            dateDays.add(index.toString())
        }
        signInDateAdapter.setAddDataNew(dateDays)


        text_sign_in_time.text = getYearMontyDay()

        text_sign_in_submit.setOnClickListener {
            viewModel.signInUser()
        }

    }

    override fun initViewMode() {
        viewModel.signInListDataLiveData.observe(this, Observer { response ->
            if (response.status != HttpResponseStatus.Status.SUCCESS)
                return@Observer
            response.response?.data?.list?.let {
                val positions: MutableList<Int> = mutableListOf()
                it.forEach { entity ->
                    val time: Long = entity.sign_time * 1000
                    positions.add(dateDays.indexOf(getDateOfDay(time).toString()))
                }
                signInDateAdapter.setSelectedItem(positions)
            }
        })

        viewModel.baseDataLiveData.observe(this, Observer { response ->
            handlerResponseLoading(response.status, response.statusTip)
            if (response.status != HttpResponseStatus.Status.SUCCESS)
                return@Observer
            toast(response.response?.msg ?: "签到成功")
            signInDateAdapter.setSelectedItem(mutableListOf(dateDays.indexOf(getDay().toString())))
        })
    }

    override fun initData() {
        viewModel.signInLog()
    }

    /**
     * 给定时间戳返回该时间对应每个月的第几天
     * */
    private fun getDateOfDay(time: Long): Int {
        val cal: Calendar = Calendar.getInstance()
        cal.time = Date(time)
        return cal[Calendar.DAY_OF_MONTH]
    }

    /**
     * 获取每个月的第一天对应星期几
     * */
    private fun getMontyFirstDayOfWeek(year: Int, month: Int): Int {
        val cal: Calendar = Calendar.getInstance()
        cal[Calendar.YEAR] = year
        cal[Calendar.MONTH] = month - 1
        cal[Calendar.DAY_OF_MONTH] = 1
        return cal[Calendar.DAY_OF_WEEK]
    }

    /**
     * 获取每个月的总天数
     * */
    private fun getMontyCountDay(year: Int, month: Int): Int {
        val cal: Calendar = Calendar.getInstance()
        cal[Calendar.YEAR] = year
        cal[Calendar.MONTH] = month - 1
        cal[Calendar.DATE] = 1
        cal.roll(Calendar.DATE, -1)
        return cal[Calendar.DATE]
    }

    /**
     * 获取当前年
     * */
    private fun getYear(): Int {
        val cal: Calendar = Calendar.getInstance()
        return cal.get(Calendar.YEAR)
    }

    /**
     * 获取当前月
     * */
    private fun getMonth(): Int {
        val cal: Calendar = Calendar.getInstance()
        return (cal.get(Calendar.MONTH)) + 1
    }

    /**
     * 获取当前天
     * */
    private fun getDay(): Int {
        val cal: Calendar = Calendar.getInstance()
        return cal.get(Calendar.DAY_OF_MONTH)
    }

    /**
     * 获取每个月的第一天
     * */
    private fun getMontyFirstDay(): String {
        val cal: Calendar = Calendar.getInstance()
        cal[Calendar.DAY_OF_MONTH] = 1
        return SimpleDateFormat(
            "yyyy-MM-dd", Locale.getDefault()
        ).format(cal.time).toString()
    }

    /**
     * 获取当前年月日
     * */
    private fun getYearMontyDay(): String {
        return SimpleDateFormat(
            "yyyy-MM-dd", Locale.getDefault()
        ).format(Date()).toString()
    }

    /**
     * 获取每个月的最后一天
     * */
    private fun getMontyLastDay(): String {
        val cal: Calendar = Calendar.getInstance()
        cal[Calendar.DAY_OF_MONTH] =
            cal.getActualMaximum(Calendar.DAY_OF_MONTH)
        return SimpleDateFormat(
            "yyyy-MM-dd", Locale.getDefault()
        ).format(cal.time).toString()
    }
}